'use strict'

import {CITY_DATA} from '../util/distpicker'
import { requestApi } from '../../../api'

const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    hidden: false,
    channel: '',
    data: {},   //个人信息
    sexArray: ['女','男'],
    index: 0,
    provinces: [],
    province: '北京市',
    citys: [],
    city: '北京市',
    districts: [],
    district: '东城区',
    condition: false,
    password: '******',
    phoneNum: '',
    address: '',
    timeDifference: 0,
  },
  // image 
  chooseImageTap: function (){
    wx.showActionSheet({
       itemList: ['从相册中选择', '拍照'],
       itemColor: "#f7982a",
       success: (res) => {
         if (!res.cancel) {
           if (res.tapIndex == 0) {
            this.chooseWxImage('album')
           } else if (res.tapIndex == 1) {
            this.chooseWxImage('camera')
           }
         }
       }
    })
  },
  chooseWxImage: function (type) {
    let that = this

    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: [type],
      success: (res)=> {
        console.log(res)
        that.uploadFile(res.tempFiles)
      }
    })
  },

  uploadFile: function (tempFiles) {
    const tempFilePaths = tempFiles[0].path
    const tempFileSize = tempFiles[0].size
    const tempArr = tempFilePaths.split('.')
    const tempFileType = tempArr[tempArr.length - 1]
    const date = new Date() 
    const timestamp = Math.floor(new Date() / 1000) + this.data.timeDifference // 时间戳 秒
    const time = `${date.getFullYear()}${date.getMonth() + 1}${date.getDate()}`
    let that = this

    let authPath = 'mars' + `/${time}`

    const params = {
      auth_path: authPath,
      file_size: tempFileSize,
      timestamp: timestamp,
      file_type: tempFileType,
    }

    app.request({
      url: requestApi.webOssAuthUrl,
      methods: 'GET',
      data: params
    }, (res) => {
      let ossKey = res.original.oss_key

      wx.uploadFile({
        url: ossKey.host,
        filePath: tempFilePaths,
        name: 'file',
        formData: {
          name: tempFilePaths,
          key: ossKey.auth_path,
          OSSAccessKeyId: ossKey.accessid,
          policy: ossKey.policy,
          signature: ossKey.signature,
          success_action_status: '200',
        },
        success() {
          let url = requestApi.setAvatarUrl
          let param = {
            'avatar_image': ossKey.auth_path,
          }

          // 调用网络请求
          app.request({
            url: url,
            data: param,
            method: 'POST'
          }, ()=> {
            // show logo
            that.setData({
              'data.avatar_image_uri': tempFilePaths,
            })
            wx.showToast({
              title: '上传成功',
            })
            wx.setStorage({
              key: 'profileinfo',
              data: that.data.data
            })
          }, (error)=> {
            wx.showModal({
              title: '提示',
              content: error,
              showCancel: false
            })
          })
        },
        fail(error) {
          wx.showModal({
            title: '提示',
            content: error,
            showCancel: false
          })
        }
      })
      
    }, (error) => {
      wx.showModal({
        title: '提示',
        content: error,
        showCancel: false
      })
    })
  },

  // 用户名绑定事件
  bindName: function (e) {
    var nickname = e.currentTarget.dataset.value
    wx.navigateTo({
      url: '../username/username?nickname=' + nickname
    })

  },
  // 性别改变绑定事件
  bindPickerChange: function (e) {
    let url = requestApi.setGenderUrl
    let data = {
      gender: e.detail.value == 0 ? 'f' : 'm'
    }
    this.setData({
      index: e.detail.value,
      'data.gender': e.detail.value == 0 ? 'f' : 'm'
    })

    // 调用网络请求
    app.request({
      url: url,
      data: data,
      method: 'POST'
    }, (res)=> {
      wx.showToast({
        title: res.original.msg,
      })
      // 存储storage
      wx.setStorage({
        key: 'profileinfo',
        data: this.data.data,
      })
    }, (error)=> {
      wx.showModal({
        title: '提示',
        content: error,
        showCancel: false
      })
    })
  },
  // 生日改变绑定事件
  bindDateChange: function (e) {
    let data = {
      birthday: e.detail.value
    }
    this.setData({
      'data.birthday': e.detail.value
    })
    
    // 调用网络请求
    app.request({
      url: requestApi.setBirthUrl,
      data: data,
      method: 'POST'
    }, (res)=> {
      wx.showToast({
        title: res.original.msg,
      })
      wx.setStorage({
        key: 'profileinfo',
        data: this.data.data,
      })
    }, (error)=> {
      wx.showModal({
        title: '提示',
        content: error,
        showCancel: false
      })
    })
  },
  // 常驻地改变事件
  bindLocationChange: function (e) {
    var val = e.detail.value
    var t = this.data.values;
    var cityData = CITY_DATA

    if (val[0] != t[0]) {
      const citys = [];
      const districts = [];

      for (let i = 0; i < cityData[val[0]].sub.length; i++) {
        citys.push(cityData[val[0]].sub[i].name)
      }
      for (let i = 0; i < cityData[val[0]].sub[0].sub.length; i++) {
        districts.push(cityData[val[0]].sub[0].sub[i].name)
      }

      this.setData({
        province: this.data.provinces[val[0]],
        city: cityData[val[0]].sub[0].name,
        citys: citys,
        district: cityData[val[0]].sub[0].sub[0].name,
        districts: districts,
        values: val,
        value: [val[0], 0, 0]
      })

      return;
    }
    if (val[1] != t[1]) {
      const districts = [];

      for (let i = 0; i < cityData[val[0]].sub[val[1]].sub.length; i++) {
        districts.push(cityData[val[0]].sub[val[1]].sub[i].name)
      }

      this.setData({
        city: this.data.citys[val[1]],
        district: cityData[val[0]].sub[val[1]].sub[0].name,
        districts: districts,
        values: val,
        value: [val[0], val[1], 0]
      })
      return;
    }
    if (val[2] != t[2]) {
      this.setData({
        district: this.data.districts[val[2]],
        values: val
      })
      return;
    }
  },
  bindLocationSure: function () {
    let province = this.data.province 
    let city = this.data.city
    let district = this.data.district 
    let residence = province + ' ' + city + ' ' + district
    let data = {
      usual_residence: residence
    }
    this.setData({
      'data.usual_residence': residence,
      'province': province,
      'city': city,
      'district': district,
      'condition': !this.data.condition
    })

    // 调用网络请求
    app.request({
      url: requestApi.setResidenceUrl,
      data: data,
      method: 'POST'
    }, (res)=> {
      wx.showToast({
        title: res.original.msg,
      })
      wx.setStorage({
        key: 'profileinfo',
        data: this.data.data,
      })
    }, (error)=> {
      wx.showModal({
        title: '提示',
        content: error,
        showCancel: false
      })
    })
  },
  choosearea: function () {
    this.setData({
      condition: !this.data.condition
    })
  },
  // 修改密码
  bindPassword: function (e) {
    wx.navigateTo({
      url: '../password/password'
    })
  },
  // 收货地址
  bindAddress: function () {
    wx.navigateTo({
      url: '../addressList/addressList',
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let channel = options.channel || 'wx_xcx'

    this.setData({
      channel: channel,
    })
    // 获取存储storage信息
    wx.getStorage({
      key: 'profileinfo',
      success: (res)=> {
        this.setData({
          data: res.data,
          hidden: true,
          index: res.data.gender == 'm' ? 1 : 0
        })
        if (this.data.data.usual_residence) {
          let residenceArr = this.data.data.usual_residence.split(' ')
          this.setData({
            province: residenceArr[0],
            city: residenceArr[1],
            district: residenceArr[2]
          })
        }

        // 初始化省份数据
        var cityData = CITY_DATA
        const provinces = [];
        const citys = [];
        const districts = [];
        // 默认省份和城市的下标索引值为0
        let provinceIndex = 0;
        let cityIndex = 0;
        let districtIndex = 0;
        let province = this.data.province
        let city = this.data.city
        let district = this.data.district

        for (let i = 0; i < cityData.length; i++) {
          provinces.push(cityData[i].name);
        }
        
        provinceIndex = provinces.indexOf(province)

        if (provinceIndex > -1) {
          for (let i = 0; i < cityData[provinceIndex].sub.length; i++) {
            citys.push(cityData[provinceIndex].sub[i].name)
          }

          cityIndex = citys.indexOf(city)

          for (let i = 0; i < cityData[provinceIndex].sub[cityIndex].sub.length; i++) {
            districts.push(cityData[provinceIndex].sub[cityIndex].sub[i].name)
          }

          districtIndex = districts.indexOf(district)
        }
       
        this.setData({
          provinces: provinces,
          citys: citys,
          districts: districts,
          value: [provinceIndex, cityIndex, districtIndex],
          values: [provinceIndex, cityIndex, 0],
          hidden: true,
        })

      },
    })
   
    // 获取个人手机号
   wx.getStorage({
      key: 'userinfo',
      success: (res)=> {
        this.setData({
          phoneNum: res.data.mobile_phone
        })
      },
    })
   
    // 获取收货地址列表的第一条数据
    app.request({
      // url: API_URL_ADDRESSLIST
      url: requestApi.addressListUrl
    }, (data) => {
      if (data.original.address_list && data.original.address_list.length) {
        let itemInfo = data.original.address_list[0]
        let address = itemInfo['province'] + ' ' + itemInfo['city'] + ' ' + itemInfo['district'] + ' ' + itemInfo['address']
        this.setData({
          address: address
        })
      }

      data.original.updatetime = data.original.updatetime.replace(/-/g, '/')

      let time = Math.floor(new Date(data.original.updatetime) / 1000) - Math.floor(new Date() / 1000)

      this.setData({
        timeDifference: time,
      })

      wx.setStorage({
        key: 'timeDifference',
        data: time,
      })
    }, (error) => {
      wx.showModal({
        title: '提示',
        content: error,
        showCancel: false,     
      })
    })
   
  },

  // 请求操作
  requestOperate: function (url, data) {
    let options = {
      url: url,
      data: data,
      method: 'POST'
    }
    app.request(
      options, 
      (data)=> {
        wx.showToast({
          title: data.original.msg,
        })
      },
      (error)=> {
        wx.showModal({
          title: '提示',
          content: error,
          showCancel: false
        })
      })

  }


})